import { defineStore } from "pinia"
import { ref, computed } from 'vue'
import { useUserStore } from './userStore'
import { insertCartAPI, findNewCartAPI,delCartAPI } from '@/apis/cart'

export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    const isLogin = computed(()=>userStore.userInfo.token)
    const cartList = ref([])
    const updateNewList = async ()=>{
        const res = await findNewCartAPI()
        cartList.value = res.result
    }
    const addCart = async (goods) => {
        const { skuId, count } = goods
        if (isLogin.value) {
            await insertCartAPI({ skuId, count })
            updateNewList()
        } else {
            const item = cartList.value.find((item) => { return goods.skuId === item.skuId })
            if (item) {
                item.count++
            } else {
                cartList.value.push(goods)
            }
        }

    }

    const delCart =async (skuId) => {
        if(isLogin.value){
          await delCartAPI([skuId])
          updateNewList()
        }else{
            cartList.value = cartList.value.filter((item) => { return item.skuId !== skuId })
        }
        
    }

    const clearCart = ()=>{
        cartList.value = []
    }

    const singeCheck = (skuId, selected) => {
        let item = cartList.value.find(item => item.skuId === skuId)
        item.selected = selected
    }

    const changeCheck = (selected) => {
        cartList.value.forEach(item =>
            item.selected = selected
        )
    }

    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))

    // cartList.value.reduce((a, c) => a + c.count, 0)

    const allPrice = computed(() => { return cartList.value.reduce((a, c) => { return a + c.count * c.price }, 0) })

    const selectedCount = computed(() => { return cartList.value.reduce((a, c) => { if (c.selected) { return a + c.count } else { return a } }, 0) })

    const selectedPrice = computed(() => { return cartList.value.reduce((a, c) => { if (c.selected) { return a + c.count * c.price } else { return a } }, 0) })

    const isAll = computed(() => {
        return cartList.value.every(item => item.selected)
    })



    return {
        cartList,
        addCart,
        delCart,
        clearCart,
        allCount,
        allPrice,
        isAll,
        changeCheck,
        singeCheck,
        selectedCount,
        selectedPrice,
        updateNewList
    }
}, {
    persist: true
})